package dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import entity.TUser;

public class TUserDao extends HibernateDao {
    public static List<TUser> getAllUser() {
        Session session = getSession();
        
        List<TUser> list = (List<TUser>) session.createCriteria(
                TUser.class).list();
        session.close();

        return list; 
    } 
    
    public static TUser getUserFromId(String id) {
        if (id == null) {
            return null;
        }
        
        Session session = getSession();
        TUser tUser = (TUser)session.load(TUser.class, id);
        session.close();
        
        return tUser;
    }
    
    public static boolean isUser(String userId, String password)
            throws Exception {
        Session session = getSession();

        List<?> list = session.createQuery(
                "select count(t) from " + "TUser t where t.userId = '" + userId
                        + "' and t.password = '" + password + "'").list();
        Long result = (Long) list.get(0);

        session.close();

        if (result == 1) {
            return true;
        } else if (result == 0) {
            return false;
        } else {
            // TODO 例外で処理しようかどうか考え中
            throw new Exception("user_table has keys more than 1.");
        }
    }
    
    public static void addUser(String userId, String userName,
            String password, String mail, Integer auth) {
        
        Session session = getSession();
        Transaction trans = session.beginTransaction();
        
        TUser tUser = new TUser();
        tUser.setUserId(userId);
        tUser.setUserName(userName);
        tUser.setPassword(password);
        tUser.setMail(mail); 
        tUser.setAuth(auth);
        
        session.save(tUser); 
        
        trans.commit();
        session.close();
    }
    
    public static void updateUser(String userId, String userName,
            String password, String mail, Integer auth) {
        Session session = getSession();
        Transaction trans = session.beginTransaction();
        
        TUser tUser = (TUser)session.load(TUser.class, userId);
        if (userName != null) {
            tUser.setUserName(userName);
        }
        if (password != null) {
            tUser.setPassword(password);
        }
        if (mail != null) {
            tUser.setMail(mail); 
        }
        if (auth != null) {
            tUser.setAuth(auth); 
        }
        
        session.update(tUser);
        
        trans.commit();
        session.close(); 
    }

}
